from subprocess import Popen, PIPE
import pymysql
import os
import logging
import optparse
parser = optparse.OptionParser()

parser.add_option('-e','--squishPath', type = 'string', dest = 'squishPath', help = 'path to squish')
parser.add_option('-l','--logsPath', type = 'string', dest = 'logsPath', help = 'path to test logs')
parser.add_option('-s','--suitesPath', type = 'string', dest = 'suitesPath', help = 'path to test suites')

class Helper(object):
    def execCapture(self, command, waitUntilFinish = True):
        p = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
        if waitUntilFinish:
            out, error = p.communicate()
            result = out if out else error
            return result.replace(os.linesep, '\n')
        else:
            return 'Process started'

def callDB(query):
    # it is hack for calling storage procedures
    # with pymysql.connect(host="localhost", user="root",
    #                      passwd="C0lombo", db="autotests", charset='utf8') as cursor:
     with pymysql.connect(host="172.16.0.30", user="testfarm",
                         passwd="C0lombo", db="autotests", charset='utf8') as cursor:

        cursor.execute(query)
        return cursor.fetchall()

def getOSId(osName):
    for osRecord in callDB('call getOSList'):
        if osName == osRecord[1]:
            return osRecord[0]
    return None


def main(squishPath = r'C:\Tests\squish', logsPath = r'C:\Tests\Logs', suitesPath = r'C:\Tests\Suites'):
    helper = Helper()
    restartCount = 0
    standaloneBMCaseId = 62
    testsRootDir = os.path.normpath('C:/Tests')
    osConfigPath = os.path.join(testsRootDir, 'StartToRun.bat')
    with open(osConfigPath, 'r') as file: _osConfigLine = file.readline().split('=')[1]
    osName = _osConfigLine.split(' ')[0].strip()
    # if osName == 'DEBUG':
    #     squishPath = r'C:\Users\alexandra.yedinovich\Documents\squish'
    #     logsPath = r'C:\Tests\Logs1'
    #     suitesPath = r'C:\trunk\QA\TestFarm\test_scripts\Suites'
    logging.basicConfig(filename='%s\StandaloneBMRunner.log' % logsPath, filemode='w', level=logging.DEBUG)
    cmd = '%s\\bin\\squishserver.exe --config addAUT "BackupManager" "c:\\Program Files\\Backup Manager"' % squishPath
    helper.execCapture(cmd)
    cmd = 'start cmd \/c "%s\\bin\\squishserver.exe >> %s\squish_server.log 2>&1"' % (squishPath, logsPath)
    helper.execCapture(cmd, waitUntilFinish=False)
    while restartCount < 4:
        timeStart = callDB('SELECT Now()')[0][0]
        logging.info("Time Start: " + str(timeStart))
        cmd = "%s\\bin\\squishrunner.exe --debugLog alpw --testsuite %s\\suite_StandaloneBM --resultdir %s" %\
              (squishPath, suitesPath, logsPath)
        result = helper.execCapture(cmd)
        logging.info("Execution test case output:\n" + result)
        timeFinish = callDB('SELECT Now()')[0][0]
        logging.info("Time Finish: " + str(timeFinish))
        caseResult = callDB('call getCaseResult(%s, %s, "%s", "%s")' % (getOSId(osName), standaloneBMCaseId, timeStart, timeFinish))[0]
        logging.info("Case Result from DB:\n" + str(caseResult))
        if caseResult == () or caseResult[0]+caseResult[1]+caseResult[2] > 0:
            restartCount = restartCount + 1
            if restartCount != 4:
                logging.info("Restarting test case for %i time..." % restartCount)
        else:
            break
    if restartCount == 4:
        logging.info("Fail to run test_case")
    else:
        logging.info("Test case was executed successfully")
    helper.execCapture('%s\\bin\\squishserver.exe --stop' % squishPath)

if __name__ == "__main__":
    options, args = parser.parse_args()
    main(options.squishPath, options.logsPath, options.suitesPath)
    #main()